package com.learn.core.controller.learn;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.JwtUtil;
import com.learn.common.utils.PageResult;
import com.learn.common.utils.ResultUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.http.OkHttps;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.*;
import com.learn.core.domain.view.CompetitionTarget;
import com.learn.core.domain.view.OperationScore;
import com.learn.core.domain.view.UserDetailsGather;
import com.learn.core.dto.LCompetitionDTO;
import com.learn.core.dto.LCompetitionNewDTO;
import com.learn.core.dto.LCompetitionSortDTO;
import com.learn.core.dto.LRotatePicturesDTO;
import com.learn.core.service.*;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName CompetitionController
 * @date 2021.06.02 08:49
 * @describe 竞赛模块
 */
@Api("竞赛模块")
@RestController
@RequestMapping("/learn/competition")
public class CompetitionController extends WebController<LCompetition> {

    @Autowired
    ILCompetitionService ilCompetitionService;
    @Autowired
    ICompetitionTargetService iCompetitionTargetService;
    @Autowired
    ILCompetitionPaperService ilCompetitionPaperService;
    @Autowired
    ILCompetitionUserService ilCompetitionUserService;
    @Autowired
    ILUserService ilUserService;
    @Autowired
    ILQuestionsService ilQuestionsService;
    @Autowired
    ILOptionService ilOptionService;
    @Autowired
    ILCompetitionAnswerService ilCompetitionAnswerService;
    @Autowired
    ILCompetitionQuestionService ilCompetitionQuestionService;
    @Autowired
    private ILCompetitionNewService ilCompetitionNewService;
    @Autowired
    private IUserDetailsGatherService iUserDetailsGatherService;
    @Autowired
    private ILOrganizationService ilOrganizationService;
    @Autowired
    private ILRotatePicturesService ilRotatePicturesService;
    @Autowired
    private ILCompetitionSortService ilCompetitionSortService;
    @Autowired
    private ILOperationService ilOperationService;
    @Autowired
    private IOperationScoreService iOperationScoreService;
    @Autowired
    private ILOperationScoreService ilOperationScoreService;
    @Autowired
    private ILCommentService ilCommentService;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //轮播图列表
    @ApiOperation(value = "轮播图列表")
    @UserLoginToken
    @PostMapping("/rotateList")
    public PageResult<LRotatePictures> rotateList(@RequestBody LRotatePicturesDTO lRotatePicturesDTO){
        try {
            if (lRotatePicturesDTO==null||lRotatePicturesDTO.getPage()==null||lRotatePicturesDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lRotatePicturesDTO.getPage(),lRotatePicturesDTO.getRows());
            QueryWrapper<LRotatePictures> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("rotate_top","1");
            queryWrapper.orderByAsc("rotate_seq");
            Page<LRotatePictures> LRotatePictures = (Page<LRotatePictures>)ilRotatePicturesService.list(queryWrapper);
            if (CollectionUtils.isEmpty(LRotatePictures)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(LRotatePictures.getTotal(), LRotatePictures, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //赛事报导
    @ApiOperation(value = "赛事报导")
    @UserLoginToken
    @PostMapping("/newList")
    public PageResult<LCompetitionNew> newList(@RequestBody LCompetitionNewDTO lCompetitionNewDTO){
        try {
            if (lCompetitionNewDTO==null||lCompetitionNewDTO.getPage()==null||lCompetitionNewDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCompetitionNewDTO.getPage(),lCompetitionNewDTO.getRows());
            QueryWrapper<LCompetitionNew> queryWrapper = new QueryWrapper<>();
            if(StringUtils.isNotEmpty(lCompetitionNewDTO.getStartTime()))
                queryWrapper.gt("create_time",lCompetitionNewDTO.getStartTime());
            if(StringUtils.isNotEmpty(lCompetitionNewDTO.getEndTime()))
                queryWrapper.le("create_time",lCompetitionNewDTO.getEndTime());
            queryWrapper.orderByAsc("competition_seq");
            Page<LCompetitionNew> lCompetitionNews = (Page<LCompetitionNew>)ilCompetitionNewService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lCompetitionNews)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LCompetitionNew lCompetitionNew: lCompetitionNews) {
                QueryWrapper<UserDetailsGather> userDetailsGatherQueryWrapper = new QueryWrapper<>();
                userDetailsGatherQueryWrapper.eq("user_id",lCompetitionNew.getCompetitionUser());
                UserDetailsGather userDetailsGather = iUserDetailsGatherService.getOne(userDetailsGatherQueryWrapper);
                if(null != userDetailsGather){
                    lCompetitionNew.setUserName(userDetailsGather.getUserName());
                    LOrganization lOrganization = ilOrganizationService.getById(userDetailsGather.getOrganizationId());
                    if(null != lOrganization)
                        lCompetitionNew.setOrganizationName(lOrganization.getOrganizationName());
                }
                QueryWrapper<LCompetitionUser> lCompetitionUserQueryWrapper = new QueryWrapper<>();
                lCompetitionUserQueryWrapper.eq("competition_id",lCompetitionNew.getCompetitionId());
                LCompetitionUser lCompetitionUser = ilCompetitionUserService.getOne(lCompetitionUserQueryWrapper);
                if(null != lCompetitionUser){
                    lCompetitionNew.setUserScore(lCompetitionUser.getUserScore());
                    lCompetitionNew.setOperationScore(lCompetitionUser.getOperationScore());
                }
                LCompetition lCompetition = ilCompetitionService.getById(lCompetitionNew.getCompetitionId());
                if(null != lCompetition){
                    lCompetitionNew.setCompetitionName(lCompetition.getCompetitionName());
                }
            }
            // 返回
            return new PageResult(lCompetitionNews.getTotal(), lCompetitionNews, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //赛事报导详情
    @ApiOperation(value = "赛事报导详情")
    @UserLoginToken
    @GetMapping("/newInfo")
    public CommonResult<Object> newInfo(@RequestParam("id")Integer id){
        try {
            LCompetitionNew lCompetitionNew = ilCompetitionNewService.getById(id);
            if(null != lCompetitionNew){
                QueryWrapper<UserDetailsGather> userDetailsGatherQueryWrapper = new QueryWrapper<>();
                userDetailsGatherQueryWrapper.eq("user_id",lCompetitionNew.getCompetitionUser());
                UserDetailsGather userDetailsGather = iUserDetailsGatherService.getOne(userDetailsGatherQueryWrapper);
                if(null != userDetailsGather){
                    lCompetitionNew.setUserName(userDetailsGather.getUserName());
                    LOrganization lOrganization = ilOrganizationService.getById(userDetailsGather.getOrganizationId());
                    if(null != lOrganization)
                        lCompetitionNew.setOrganizationName(lOrganization.getOrganizationName());
                }
                QueryWrapper<LCompetitionUser> lCompetitionUserQueryWrapper = new QueryWrapper<>();
                lCompetitionUserQueryWrapper.eq("competition_id",lCompetitionNew.getCompetitionId());
                LCompetitionUser lCompetitionUser = ilCompetitionUserService.getOne(lCompetitionUserQueryWrapper);
                if(null != lCompetitionUser){
                    lCompetitionNew.setUserScore(lCompetitionUser.getUserScore());
                    lCompetitionNew.setOperationScore(lCompetitionUser.getOperationScore());
                }
                LCompetition lCompetition = ilCompetitionService.getById(lCompetitionNew.getCompetitionId());
                if(null != lCompetition){
                    lCompetitionNew.setCompetitionName(lCompetition.getCompetitionName());
                }
            }
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lCompetitionNew);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //竞赛分类列表
    @ApiOperation(value = "竞赛分类列表")
    @UserLoginToken
    @PostMapping("/sortList")
    public PageResult<LCompetitionSort> sortList(@RequestBody LCompetitionSortDTO lCompetitionSortDTO){
        try {
            if (lCompetitionSortDTO==null||lCompetitionSortDTO.getPage()==null||lCompetitionSortDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCompetitionSortDTO.getPage(),lCompetitionSortDTO.getRows());
            QueryWrapper<LCompetitionSort> queryWrapper = new QueryWrapper<LCompetitionSort>();
            if(lCompetitionSortDTO.getParentNode()!=null)
                queryWrapper.eq("parent_node",lCompetitionSortDTO.getParentNode());
            else {
                queryWrapper.eq("parent_node","0");
            }
            if(lCompetitionSortDTO.getCompetitionSortName()!=null)
                queryWrapper.like("competition_sort_name",lCompetitionSortDTO.getCompetitionSortName());
            Page<LCompetitionSort> lCompetitionSorts = (Page<LCompetitionSort>) ilCompetitionSortService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lCompetitionSorts)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(lCompetitionSorts.getTotal(), lCompetitionSorts, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //理论竞赛列表
    @ApiOperation(value = "理论竞赛列表")
    @UserLoginToken
    @PostMapping("/list")
    public PageResult<CompetitionTarget>  list(@RequestBody LCompetitionDTO lCompetitionDTO,HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if (lCompetitionDTO==null||lCompetitionDTO.getPage()==null||lCompetitionDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCompetitionDTO.getPage(),lCompetitionDTO.getRows());
            QueryWrapper<CompetitionTarget> queryWrapper = new QueryWrapper<CompetitionTarget>();
            queryWrapper.eq("competition_sort",lCompetitionDTO.getCompetitionSort());
            queryWrapper.eq("release_state","1");
            queryWrapper.orderByAsc("release_time");
            Page<CompetitionTarget> competitionTargets = (Page<CompetitionTarget>) iCompetitionTargetService.list(queryWrapper);
            if (CollectionUtils.isEmpty(competitionTargets)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (CompetitionTarget competitionTarget : competitionTargets) {
                // 查询已考次数
                QueryWrapper<LCompetitionUser> userQueryWrapper = new QueryWrapper<LCompetitionUser>();
                userQueryWrapper.eq("competition_id",competitionTarget.getCompetitionId());
                userQueryWrapper.eq("user_id",userId);
                int frequency = ilCompetitionUserService.count(userQueryWrapper);
                if(frequency > 0)
                    competitionTarget.setFrequency(frequency);
                else
                    competitionTarget.setFrequency(0);
            }
            return new PageResult(competitionTargets.getTotal(), competitionTargets, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //报名考试
    @ApiOperation(value = "报名考试")
    @UserLoginToken
    @PostMapping("/enroll")
    public CommonResult<Object> enroll(@RequestBody LCompetitionUser lCompetitionUser, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(null != lCompetitionUser){
                if(StringUtils.isEmpty(lCompetitionUser.getCompetitionId()))
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COMPETITION_ID);
                QueryWrapper<LCompetitionPaper> queryWrapper = new QueryWrapper<LCompetitionPaper>();
                queryWrapper.eq("competition_id",lCompetitionUser.getCompetitionId());
                queryWrapper.last("order by rand() LIMIT 1");
                LCompetitionPaper lCompetitionPaper = ilCompetitionPaperService.getOne(queryWrapper);
                if(null != lCompetitionPaper)
                    lCompetitionUser.setCompetitionPaperId(lCompetitionPaper.getCompetitionPaperId());
                lCompetitionUser.setUserIp(OkHttps.getIpAddr(request));
                lCompetitionUser.setUserId(Integer.parseInt(userId));
                lCompetitionUser.setCreateTime(new Date());
                lCompetitionUser.setPaperState("1");
                if(ilCompetitionUserService.save(lCompetitionUser))
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lCompetitionUser.getCompetitionUserId());
            }
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //竞赛详情
    @ApiOperation(value = "竞赛详情")
    @UserLoginToken
    @GetMapping("/info")
    public CommonResult<Object> info(@RequestParam("id")Integer id, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            LCompetitionUser lCompetitionUser = ilCompetitionUserService.getById(id);

            // 竞赛问题
            LCompetitionPaper lCompetitionPaper = ilCompetitionPaperService.getById(lCompetitionUser.getCompetitionPaperId());
            Map<String,Object> map = new HashMap<>();
            LUser lUser = ilUserService.getById(lCompetitionUser.getUserId());
            map.put("user",lUser);
            map.put("competitionUserId",id);
            LCompetition lCompetition = ilCompetitionService.getById(lCompetitionUser.getCompetitionId());
            map.put("lCompetition",lCompetition);
            Map<String,Object> questionMap = new HashMap<>();
            String question = lCompetitionPaper.getCompetitionQuestionsId();
            JSONObject json = JSONObject.fromObject(question);
            if(StringUtils.isNotEmpty(json.get("check"))){
                List<Integer> list = (List) json.get("check");
                List<LQuestions> lQuestionsList = new ArrayList<>();
                for (Integer integer : list) {
                    LQuestions lQuestions = ilQuestionsService.getById(integer);
                    if(null != lQuestions){
                        QueryWrapper<LOption> queryLOption = new QueryWrapper<LOption>();
                        queryLOption.eq("questions_id",lQuestions.getQuestionsId());
                        List<LOption> lOptionList = ilOptionService.list(queryLOption);
                        lQuestions.setlOptionList(lOptionList);
                    }
                    lQuestionsList.add(lQuestions);
                }
                questionMap.put("check",lQuestionsList);
            }
            if(StringUtils.isNotEmpty(json.get("judge"))){
                List<Integer> list = (List) json.get("judge");
                List<LQuestions> lQuestionsList = new ArrayList<>();
                for (Integer integer : list) {
                    LQuestions lQuestions = ilQuestionsService.getById(integer);
                    if(null != lQuestions){
                        QueryWrapper<LOption> queryLOption = new QueryWrapper<LOption>();
                        queryLOption.eq("questions_id",lQuestions.getQuestionsId());
                        List<LOption> lOptionList = ilOptionService.list(queryLOption);
                        lQuestions.setlOptionList(lOptionList);
                    }
                    lQuestionsList.add(lQuestions);
                }
                questionMap.put("judge",lQuestionsList);
            }
            if(StringUtils.isNotEmpty(json.get("radio"))){
                List<Integer> list = (List) json.get("radio");
                List<LQuestions> lQuestionsList = new ArrayList<>();
                for (Integer integer : list) {
                    LQuestions lQuestions = ilQuestionsService.getById(integer);
                    if(null != lQuestions){
                        QueryWrapper<LOption> queryLOption = new QueryWrapper<LOption>();
                        queryLOption.eq("questions_id",lQuestions.getQuestionsId());
                        List<LOption> lOptionList = ilOptionService.list(queryLOption);
                        lQuestions.setlOptionList(lOptionList);
                    }
                    lQuestionsList.add(lQuestions);
                }
                questionMap.put("radio",lQuestionsList);
            }
            map.put("questions",questionMap);
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //个人答题情况
    @ApiOperation(value = "个人答题情况")
    @UserLoginToken
    @GetMapping("/userAnswer")
    public CommonResult<Object> userAnswer(@RequestParam("id")Integer id, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            LCompetitionUser lCompetitionUser = ilCompetitionUserService.getById(id);
            QueryWrapper<LCompetitionAnswer> lUserAnswerQueryWrapper = new QueryWrapper<LCompetitionAnswer>();
            lUserAnswerQueryWrapper.eq("competition_user_id",lCompetitionUser.getCompetitionUserId());
            List<LCompetitionAnswer> lCompetitionAnswers = ilCompetitionAnswerService.list(lUserAnswerQueryWrapper);
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lCompetitionAnswers);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //答题
    @ApiOperation(value = "答题")
    @UserLoginToken
    @PostMapping("/saveAnswer")
    public CommonResult<Object> saveAnswer(@RequestBody LCompetitionAnswer lCompetitionAnswer){
        try {
            if(ilCompetitionAnswerService.save(lCompetitionAnswer))
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //提交试卷
    @ApiOperation(value = "提交试卷")
    @UserLoginToken
    @GetMapping("/save")
    public CommonResult<Object> save(@RequestParam("competitionUserId")Integer competitionUserId,
                                     @RequestParam("competitionTime")String competitionTime,
                                     HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            // 报名记录
            LCompetitionUser lCompetitionUser = ilCompetitionUserService.getById(competitionUserId);
            // 考次
            LCompetition lCompetition = ilCompetitionService.getById(lCompetitionUser.getCompetitionId());
            // 考试记录
            QueryWrapper<LCompetitionAnswer> answerQueryWrapper = new QueryWrapper<LCompetitionAnswer>();
            answerQueryWrapper.eq("competition_user_id",lCompetitionUser.getCompetitionUserId());
            List<LCompetitionAnswer> answerList = ilCompetitionAnswerService.list(answerQueryWrapper);
            int scores = 0;
            for (LCompetitionAnswer lCompetitionAnswer : answerList) {
                LQuestions lQuestions = ilQuestionsService.getById(lCompetitionAnswer.getQuestionsId());
                String [] answer = lQuestions.getQuestionsAnswer().split(",");
                String [] userAnswer =lCompetitionAnswer.getUserAnswer().split(",");
                if(StringUtils.equalsIgnoreOrder(answer,userAnswer)){
                    if("1".equals(lCompetition.getFractionType())){
                        scores += lQuestions.getQuestionsFraction();
                    }else{
                        QueryWrapper<LCompetitionQuestion> questionQueryWrapper = new QueryWrapper<LCompetitionQuestion>();
                        questionQueryWrapper.eq("competition_id",lCompetitionUser.getCompetitionId());
                        questionQueryWrapper.eq("competition_type_id",lQuestions.getQuestionsType());
                        LCompetitionQuestion lCompetitionQuestion = ilCompetitionQuestionService.getOne(questionQueryWrapper);
                        scores += Integer.parseInt(lCompetitionQuestion.getCompetitionFraction());
                    }
                }
            }
            LCompetitionUser competitionUser = new LCompetitionUser();
            competitionUser.setCompetitionUserId(lCompetitionUser.getCompetitionUserId());
            competitionUser.setPaperState("1");
            competitionUser.setCompetitionTime(new Date());
            competitionUser.setCompetitionUserTime(competitionTime);
            competitionUser.setUserScore(Integer.toString(scores));
            if(ilCompetitionUserService.updateById(competitionUser)){
                Map<String,Object> map = new HashMap<>();
                map.put("score",Integer.toString(scores));
                map.put("time",competitionTime);
                QueryWrapper<LCompetitionUser> queryWrapper = new QueryWrapper<LCompetitionUser>();
                queryWrapper.eq("competition_id",competitionUser.getCompetitionId());
                queryWrapper.orderByDesc("user_score");
                queryWrapper.last("limit 0,5");
                List<LCompetitionUser> competitionUsers = ilCompetitionUserService.list(queryWrapper);
                List<Map<String,Object>> list = new ArrayList<>();
                for (LCompetitionUser user: competitionUsers) {
                    Map<String,Object> userMap = new HashMap<>();
                    userMap.put("id",user.getCompetitionId());
                    QueryWrapper<UserDetailsGather> UserDetailsGather = new QueryWrapper<UserDetailsGather>();
                    UserDetailsGather.eq("user_id",user.getUserId());
                    UserDetailsGather userDetailsGather = iUserDetailsGatherService.getOne(UserDetailsGather);
                    if(null != userDetailsGather)
                        userMap.put("name",userDetailsGather.getName());
                    userMap.put("score",user.getUserScore());
                    list.add(userMap);
                }
                map.put("list",list);
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,map);
            }

        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //排行理论竞赛列表
    @ApiOperation(value = "排行理论竞赛列表")
    @UserLoginToken
    @PostMapping("/rankingList")
    public PageResult<CompetitionTarget> rankingList(@RequestBody LCompetitionDTO lCompetitionDTO){
        try {
            if (lCompetitionDTO==null||lCompetitionDTO.getPage()==null||lCompetitionDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCompetitionDTO.getPage(),lCompetitionDTO.getRows());
            QueryWrapper<CompetitionTarget> queryWrapper = new QueryWrapper<CompetitionTarget>();
            if(StringUtils.isNotEmpty(lCompetitionDTO.getCompetitionSort()))
                queryWrapper.eq("competition_sort",lCompetitionDTO.getCompetitionSort());
            queryWrapper.eq("release_state","1");
            queryWrapper.orderByAsc("release_time");
            Page<CompetitionTarget> competitionTargets = (Page<CompetitionTarget>) iCompetitionTargetService.list(queryWrapper);

            if (CollectionUtils.isEmpty(competitionTargets)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(competitionTargets.getTotal(), competitionTargets, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }


    //考试排行
    @ApiOperation(value = "考试排行")
    @UserLoginToken
    @PostMapping("/ranking")
    public CommonResult<Object> ranking(@RequestParam("competitionId")Integer competitionId){
        try {
            QueryWrapper<LCompetitionUser> queryWrapper = new QueryWrapper<LCompetitionUser>();
            queryWrapper.eq("competition_id",competitionId);
            queryWrapper.orderByDesc("user_score");
            List<LCompetitionUser> competitionUsers = ilCompetitionUserService.list(queryWrapper);
            List<Map<String,Object>> list = new ArrayList<>();
            for (LCompetitionUser user: competitionUsers) {
                Map<String,Object> userMap = new HashMap<>();
                userMap.put("id",user.getCompetitionId());
                QueryWrapper<UserDetailsGather> UserDetailsGather = new QueryWrapper<UserDetailsGather>();
                UserDetailsGather.eq("user_id",user.getUserId());
                UserDetailsGather userDetailsGather = iUserDetailsGatherService.getOne(UserDetailsGather);
                userMap.put("user_id",user.getUserId());
                if(null != userDetailsGather)
                    userMap.put("name",userDetailsGather.getName());
                userMap.put("score",user.getUserScore());
                list.add(userMap);
            }
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //用户考试信息
    @ApiOperation(value = "用户考试信息")
    @UserLoginToken
    @GetMapping("/userMatch")
    public CommonResult<Object> userMatch( @RequestParam("competitionId")Integer competitionId,HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if (competitionId==null){
                return (CommonResult) ResultUtil.error(ResultEnum.LOAD_ERROR);
            }
            Map<String,Object> map = new HashMap<>();
            QueryWrapper<UserDetailsGather> userDetailsGatherQueryWrapper = new QueryWrapper<UserDetailsGather>();
            userDetailsGatherQueryWrapper.eq("user_id",userId);
            UserDetailsGather userDetailsGather = iUserDetailsGatherService.getOne(userDetailsGatherQueryWrapper);
            map.put("user",userDetailsGather);
            LCompetition lCompetition = ilCompetitionService.getById(competitionId);
            map.put("lCompetition",lCompetition);
            QueryWrapper<LOperation> queryWrapper = new QueryWrapper<LOperation>();
            queryWrapper.eq("competition_id",competitionId);
            queryWrapper.eq("operation_user_id",userId);
            LOperation lOperation = ilOperationService.getOne(queryWrapper);
            if(null != lOperation){
                map.put("operationState","1");
                if(StringUtils.isNotEmpty(lOperation.getOperationUrl())){
                    map.put("operationUrl","1");
                }
            }else{
                map.put("operationState","0");
                map.put("operationUrl","0");
            }
            // 返回
            return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
    }


    //专家实操列表
    @ApiOperation(value = "专家实操列表")
    @UserLoginToken
    @PostMapping("/matchExpertList")
    public PageResult<OperationScore> matchExpertList(@RequestBody LCompetitionDTO lCompetitionDTO,HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if (lCompetitionDTO==null||lCompetitionDTO.getPage()==null||lCompetitionDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCompetitionDTO.getPage(),lCompetitionDTO.getRows());
            QueryWrapper<OperationScore> queryWrapper = new QueryWrapper<OperationScore>();
            queryWrapper.eq("competition_id",lCompetitionDTO.getCompetitionId());
            queryWrapper.eq("operation_user_id",userId);
            Page<OperationScore> operationScoreList = (Page<OperationScore>) iOperationScoreService.list(queryWrapper);
            if (CollectionUtils.isEmpty(operationScoreList)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(operationScoreList.getTotal(), operationScoreList, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //专家实操打分
    @ApiOperation(value = "专家实操打分")
    @UserLoginToken
    @PostMapping("/saveExpertScore")
    public CommonResult<Object> saveExpertScore(@RequestBody LOperationScore lOperationScore,HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            lOperationScore.setOperationUserId(Integer.parseInt(userId));
            if(ilOperationScoreService.save(lOperationScore)){
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
            }
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //用户实操列表
    @ApiOperation(value = "用户实操列表")
    @UserLoginToken
    @PostMapping("/matchUserList")
    public PageResult<LOperation> matchUserList(@RequestBody LCompetitionDTO lCompetitionDTO,HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if (lCompetitionDTO==null||lCompetitionDTO.getPage()==null||lCompetitionDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCompetitionDTO.getPage(),lCompetitionDTO.getRows());
            QueryWrapper<LOperation> queryWrapper = new QueryWrapper<LOperation>();
            queryWrapper.eq("competition_id",lCompetitionDTO.getCompetitionId());
            Page<LOperation> operationScoreList = (Page<LOperation>) ilOperationService.list(queryWrapper);
            if (CollectionUtils.isEmpty(operationScoreList)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LOperation lOperation : operationScoreList) {
                //专家打分情况
                QueryWrapper<LOperationScore> scoreQueryWrapper = new QueryWrapper<LOperationScore>();
                scoreQueryWrapper.eq("operation_id",lOperation.getOperationId());
                List<LOperationScore> lOperationScores = ilOperationScoreService.list(scoreQueryWrapper);
                lOperation.setOperationScoreList(lOperationScores);
                // 评论
                QueryWrapper<LComment> commentQueryWrapper = new QueryWrapper<LComment>();
                commentQueryWrapper.eq("operation_id",lOperation.getOperationId());
                List<LComment> commentList = ilCommentService.list(commentQueryWrapper);
                lOperation.setCommentList(commentList);
                lOperation.setCommentCount(commentList.size());
            }
            // 返回
            return new PageResult(operationScoreList.getTotal(), operationScoreList, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //实操点赞
    @ApiOperation(value = "实操点赞 1点赞2取消点赞")
    @UserLoginToken
    @PostMapping("/spotPraise")
    public CommonResult<Object> spotPraise(@RequestParam("operationId") Integer operationId,
                                           @RequestParam("type")String type){
        try {
            LOperation lOperation = ilOperationService.getById(operationId);
            int praise = lOperation.getPraiseCount();
            if(praise > 0){
                if("1".equals(type)){
                    praise += 1;
                }else{
                    praise -= 1;
                }
            }
            lOperation.setPraiseCount(praise);
            if(ilOperationService.save(lOperation))
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //实操评论
    @ApiOperation(value = "实操评论")
    @UserLoginToken
    @PostMapping("/saveComment")
    public CommonResult<Object> saveComment(@RequestParam("operationId") Integer operationId,
                                           @RequestParam("comment")String comment,HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            LComment lComment = new LComment();
            lComment.setOperationId(operationId);
            lComment.setCommentUser(Integer.parseInt(userId));
            lComment.setCommentContent(comment);
            lComment.setCreateTime(new Date());
            if(ilCommentService.save(lComment))
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //评论列表
    @ApiOperation(value = "评论列表")
    @UserLoginToken
    @PostMapping("/commentList")
    public PageResult<LComment> commentList(@RequestBody LCompetitionDTO lCompetitionDTO){
        try {
            if(lCompetitionDTO==null||lCompetitionDTO.getPage()==null||lCompetitionDTO.getRows()==null){
                return new PageResult<LComment>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCompetitionDTO.getPage(),lCompetitionDTO.getRows());
            QueryWrapper<LComment> commentQueryWrapper = new QueryWrapper<LComment>();
            commentQueryWrapper.eq("operation_id",lCompetitionDTO.getOperationId());
            Page<LComment> lComments = (Page<LComment>) ilCommentService.list(commentQueryWrapper);
            if (CollectionUtils.isEmpty(lComments)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(lComments.getTotal(), lComments, ResultEnum.SUCCESS);
        }catch (Exception e){
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

}
